package com.baizhi.aspect;


import com.baizhi.annotation.AddLog;
import com.baizhi.entity.Admin;
import com.baizhi.entity.Log;
import com.baizhi.service.LogService;
import com.baizhi.util.UUIDUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration   //设置一个配置类交给工厂去管理

@Aspect   //该类是一个切面类
public class LogAspect {

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Resource
    HttpServletRequest request;

    @Resource
    LogService logService;

    //根据注释添加日志
    @Around("@annotation(com.baizhi.annotation.AddLog)")
    public Object AddLog(ProceedingJoinPoint proceedingJoinPoint){

        System.out.println("----------进入环绕通知------------");

        //用户
        Admin admin = (Admin) request.getServletContext().getAttribute("admin");

        //时间
        Date date = new Date();

        //操作的方法名
        String nethodName = proceedingJoinPoint.getSignature().getName();

        //获取方法的Signature对象
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

        //获取方法
        Method method = signature.getMethod();

        //获取方法上的注解
        AddLog addLog = method.getAnnotation(AddLog.class);

        //获取注解上的属性值
        String value = addLog.value();


        String status =null;
        Object result =null;

        try {
            //放行通知执行目标方法
            result = proceedingJoinPoint.proceed();
            status="Success(执行成功)";
        } catch (Throwable e) {
            e.printStackTrace();
            status="Error(执行失败)";
            throw new RuntimeException(e.getMessage());
        }finally {
            Log log = new Log(null, admin.getUsername(), new Date(), nethodName+"("+value+")",status);

            LogAspect.log.info("管理员登录日志：{}",log);

            logService.add(log);
        }



        return result;
    }

}
